//
//  LogManager.m
//  project
//
//  Created by 圆圆陈 on 2018/4/2.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "LogManager.h"

// 日志文件保存目录
static const NSString* LogFilePath = @"/Documents/EveryDayLog/";

@interface LogManager()
// 日期格式化
@property (nonatomic,retain) NSDateFormatter* dateFormatter;
// 时间格式化
@property (nonatomic,retain) NSDateFormatter* timeFormatter;


@end

@implementation LogManager
+ (instancetype) sharedInstance{
    
    static LogManager* instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!instance) {
            instance = [[LogManager alloc]init];
        }
    });
    
    return instance;
}
// 获取当前时间
+ (NSDate*)getCurrDate{
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date dateByAddingTimeInterval: interval];
    
    return localeDate;
}
- (instancetype)init{
    
    self = [super init];
    if (self) {
        [self clearExpiredLog];
        // 创建日期格式化
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        // 设置时区，解决8小时
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        self.dateFormatter = dateFormatter;
        
        // 创建时间格式化
        NSDateFormatter* timeFormatter = [[NSDateFormatter alloc]init];
        [timeFormatter setDateFormat:@"HH:mm:ss"];
        [timeFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        self.timeFormatter = timeFormatter;
        self.breakTimes = 0;
        self.errorTimes = 0;
        if ([[NSUserDefaults standardUserDefaults] objectForKey:[NSDate date].dateToDayString]) {
            self.errorTimes = [[NSUserDefaults standardUserDefaults] integerForKey:[NSDate date].dateToDayString];
        }
        // 日志的目录路径
        self.basePath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),LogFilePath];
    }
    return self;
}
-(void)writeWithHeader:(NSString *)header WithContent:(NSString *)content WithFooter:(NSString *)footer{
    NSString* fileName = [self.dateFormatter stringFromDate:[NSDate date]];
    NSString* filePath = [NSString stringWithFormat:@"%@%@%@",self.basePath,fileName,@".txt"];
    
    // [时间]:[模块]-日志内容
    NSString* timeStr = [self.timeFormatter stringFromDate:[LogManager getCurrDate]];
    NSString* writeStr = [NSString stringWithFormat:@"[%@]:",timeStr];
    if (header!=nil && content==nil && footer==nil) {
        writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"类型:%@\n",header]];
    }else if (header==nil && content!=nil && footer==nil){
        if ([content isEqualToString:@""]) {
            writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"\n"]];
        }else{
            writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"%@\n",content]];
        }
    }else if (header==nil && content==nil && footer!=nil){
        writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"分析:%@\n",footer]];
    }else if (header!=nil && content!=nil && footer==nil){
        writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"类型:%@\n[%@]:%@\n",header,timeStr,content]];
    }else if (header!=nil && content!=nil && footer!=nil){
        writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"类型:%@\n[%@]:%@\n[%@]:分析:%@\n",header,timeStr,content,timeStr,footer]];
    }else if(header!=nil && content==nil && footer!=nil){
         writeStr = [writeStr stringByAppendingString:[NSString stringWithFormat:@"类型:%@\n[%@]:分析:%@\n",header,timeStr,footer]];
    }
    if (writeStr.length > 0) {
        // 写入数据
        [self writeFile:filePath stringData:writeStr];
    }
}
- (void)writeFile:(NSString*)filePath stringData:(NSString*)stringData{
    
    // 待写入的数据
    NSData* writeData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    
    // NSFileManager 用于处理文件
    BOOL createPathOk = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:[filePath stringByDeletingLastPathComponent] isDirectory:&createPathOk]) {
        // 目录不存先创建
        [[NSFileManager defaultManager] createDirectoryAtPath:[filePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        // 文件不存在，直接创建文件并写入
        [writeData writeToFile:filePath atomically:NO];
    }else{
        
        // NSFileHandle 用于处理文件内容
        // 读取文件到上下文，并且是更新模式
        NSFileHandle* fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
        
        // 跳到文件末尾
        [fileHandler seekToEndOfFile];
        
        // 追加数据
        [fileHandler writeData:writeData];
        
        // 关闭文件
        [fileHandler closeFile];
    }
}
- (void)clearExpiredLog{
    
    // 获取日志目录下的所有文件
    NSArray* files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.basePath error:nil];
    files = [files sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    if (files.count==8) {
        NSString *file = files.lastObject;
        [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@",self.basePath,file] error:nil];
    }
}
@end
